<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Airport extends Stourweb_Controller
{


    public function before()
    {

        parent::before();
        $action = $this->request->action();

    }

    /*
     * 机场列表
     */
    public function action_index()
    {

        $action = $this->params['action'];
        if (empty($action))
        {
            $this->display('stourtravel/airport/index');
        }
        else if ($action == 'read')
        {
            $node = Arr::get($_GET, 'node');
            $pid = $node == 'root' ? 0 : $node;
            $sql = "select * from sline_airport where pid=$pid";
            $list = DB::query(Database::SELECT, $sql)->execute()->as_array();
            foreach($list as &$row)
            {
                $row['leaf']=$row['type']==2?true:false;
            }
            $list[] = array(
                'leaf' => true,
                'id' => $pid . 'add',
                'name' => '<button class="dest-add-btn df-add-btn" onclick="addSub(' . $pid . ')">添加</button>',
                'allowDrag' => false,
                'allowDrop' => false,
                'type' => '',
                'code' => '',
                'english' => '',
                'issystem' => ''
            );
            echo json_encode(array('success' => true, 'text' => '', 'children' => $list));

        }
        else if ($action == 'update')
        {
            $id = Arr::get($_POST, 'id');
            $field = Arr::get($_POST, 'field');
            $val = Arr::get($_POST, 'val');

        }
        else if ($action == 'save')
        {
            $pinyin = '';
            $rawdata = file_get_contents('php://input');
            $data = json_decode($rawdata,true);
            $model = ORM::factory('airport',$data['id']);
            if($model->loaded())
            {
                $model->name = $data['name'];
                $model->english = $data['english'];
                $model->code= $data['code'];
                $model->type = $data['type'];
                $model->save();
                if($model->saved())
                {
                    echo 'ok';
                }
            }
        }
        else if ($action == 'addsub')
        {
            $pid = Arr::get($_POST, 'pid');
            $model = ORM::factory('airport');
            $model->name = $_POST['name'];
            $model->english = $_POST['english'];
            $model->type = $_POST['type'];
            $model->code = $_POST['code'];
            $model->pid=$pid;
            $model->save();
            if($model->saved())
            {
                $data = $model->as_array();
                $data['leaf'] = $data['type']==2?true:false;
                echo json_encode(array('status'=>true,'data'=>$data));
            }
            else
            {
                echo json_encode(array('status'=>false));
            }


        }
        else if ($action == 'search')
        {
            $keyword = trim(Arr::get($_POST, 'keyword'));
            $list = DB::query(Database::SELECT, "select id,pid from sline_airport where name like '%{$keyword}%' or code like '%{$keyword}%'")->execute()->as_array();
            $new_arr = array();

            foreach ($list as $k => $v)
            {
                $temp_arr = array();
                if ($v['pid'] != 0)
                {
                    $temp_id = $v['pid'];
                    $temp_arr = array($v['pid'], $v['id']);
                    while (true)
                    {
                        $temp_dest = ORM::factory('airport', $temp_id)->as_array();
                        if ($temp_dest['pid'] != 0)
                        {
                            array_unshift($temp_arr, $temp_dest['pid']);
                            $temp_id = $temp_dest['pid'];
                        }
                        else
                            break;
                    }

                    $new_arr[] = $temp_arr;

                }
                else
                {
                    $new_arr[] = array($v['id']);
                }


            }
            if (empty($new_arr))
                echo 'no';
            else
                echo json_encode($new_arr);
        }
        else if ($action == 'delete')
        {
            $rawdata = file_get_contents('php://input');
            $data = json_decode($rawdata,true);

            $model = ORM::factory('airport',$data['id']);
            $model->delete_clear();
        }
    }
    /*
     * 航空公司列表
     */
    public function action_airline()
    {
        $action = $this->params['action'];
        if (empty($action))  //显示列表
        {
            $this->display('stourtravel/airport/airline');
        }
        else if ($action == 'read')    //读取列表
        {
            $start = $_GET['start'];
            $limit = $_GET['limit'];
            $keyword = $_GET['keyword'];
            $sort = json_decode($_GET['sort'], true);
            if ($sort[0]['property'])
            {
                $order = 'order by '.$sort[0]['property'] . ' ' . $sort[0]['direction'];
            }
            $w='';
            if (!empty($keyword))
            {
                $w = "where (name like '%{$keyword}%' or code like '%{$keyword}%')";
            }
            $sql = "select *  from sline_airline $w $order limit $start,$limit";
            //echo $sql;
            $totalcount_arr = DB::query(Database::SELECT, "select count(*) as num from sline_airline $w ")->execute()->as_array();
            $list = DB::query(Database::SELECT, $sql)->execute()->as_array();
            $new_list = array();
            foreach ($list as $k => $v)
            {
                $new_list[] = $v;
            }
            $result['total'] = $totalcount_arr[0]['num'];
            $result['lists'] = $new_list;
            $result['success'] = true;
            echo json_encode($result);
        }
        else if ($action == 'save')   //保存字段
        {
        }
        else if ($action == 'delete') //删除某个记录
        {
            $rawdata = file_get_contents('php://input');
            $data = json_decode($rawdata);
            $id = $data->id;
            if (is_numeric($id)) //
            {
                $model = ORM::factory('airline', $id);
                $model->delete();
            }
        }
        else if ($action == 'update')//更新某个字段
        {
            $id = Arr::get($_POST, 'id');
            $field = Arr::get($_POST, 'field');
            $val = Arr::get($_POST, 'val');

            if ($field == 'displayorder')  //如果是排序
            {
                $val = empty($val) ? 9999 : $val;
            }
            $value_arr[$field] = $val;
            $isupdated = DB::update('airline')->set($value_arr)->where('id','=',$id)->execute();
            if($isupdated)
                echo 'ok';
            else
                echo 'no';
        }
    }
    /*
     * 添加或修改机场对话框
     */
    public function action_dialog_edit()
    {
        $pid = $this->params['pid'];
        $id = $this->params['id'];
        $model = ORM::factory('airport',$id);
        if($model->loaded())
        {
            $info = $model->as_array();
            $this->assign('info',$info);
        }
        $this->assign('pid',$pid);
        $this->display('stourtravel/airport/dialog_edit');
    }
    /*
     *添加或修改航空公司对话框
     */
    public function action_dialog_airline_edit()
    {
        $id = $this->params['id'];
        $model = ORM::factory('airline',$id);
        if($model->loaded())
        {
            $info = $model->as_array();
            $this->assign('info',$info);
        }
        $this->display('stourtravel/airport/dialog_airline_edit');
    }

    /*
     * 添加修改航空公司
     */
    public function action_ajax_airline_save()
    {
        $id = $_POST['id'];
        $model = ORM::factory('airline',$id);
        $model->name = $_POST['name'];
        $model->code = $_POST['code'];
        $model->save();
        echo json_encode(array('status'=>true));
    }

    public function action_import_excel()
    {
        /*
        //导入机场
        include BASEPATH.'/tools/lib/phpexcel/PHPExcel.php';
        $objReader = PHPExcel_IOFactory::createReader('Excel2007');
        $objReader->setReadDataOnly(TRUE);
        $objPHPExcel = $objReader->load(BASEPATH."/airportcode.xlsx");
        $objWorksheet = $objPHPExcel->getActiveSheet();
        $list=array();
        $number=0;
        foreach ($objWorksheet->getRowIterator() as $row) {
              if($number==0)
              {
                  $number++;
                  continue;
              }

            $cellIterator = $row->getCellIterator();
            $cellIterator->setIterateOnlyExistingCells(FALSE); // This loops through all cells,

            $i=0;

            $row=array();
            foreach ($cellIterator as $cell) {
                    $val=$cell->getValue() ;
                 switch($i)
                 {
                     case 0:
                         $row['province']= $val;
                         break;
                     case 1:
                         $row['city']=$val;
                         break;
                     case 2:
                         $row['code']=$val;
                         break;
                     case 3:
                         $row['airport']=$val;
                         break;
                     case 4:
                         $row['english'] = $val;
                         break;
                 }
                 $i++;
            }
            $list[]=$row;

        }

        $spec_provs = array('北京','上海');
        foreach($list as $row)
        {
            $city = in_array($row['province'],$spec_provs)? $row['province']:$row['city'];
            $cityid = DB::select('id')->from('airport')->where('name','=',$city)->and_where('type','=',1)->execute()->get('id');
            if(empty($cityid))
            {
                $model = ORM::factory('airport');
                $model->pid=1;
                $model->name = $city;
                $model->type=1;
                $model->english = $row['english'];
                $model->save();
                $cityid = $model->id;
            }

            $airportid = DB::select('id')->from('airport')->where('code','=',$row['code'])->and_where('type','=',2)->execute()->get('id');
            if(empty($airportid))
            {
                $model = ORM::factory('airport');
                $model->pid=$cityid;
                $model->type=2;
                $model->name = $row['airport'];
                $model->code = $row['code'];
                $model->save();
            }

        }

       */

        /*
        //导入门店
        include BASEPATH.'/tools/lib/phpexcel/PHPExcel.php';
        $objReader = PHPExcel_IOFactory::createReader('Excel2007');
        $objReader->setReadDataOnly(TRUE);
        $objPHPExcel = $objReader->load(BASEPATH."/airline.xlsx");
        $objWorksheet = $objPHPExcel->getActiveSheet();
        $list=array();
        $number=0;
        foreach ($objWorksheet->getRowIterator() as $row) {
            if($number==0)
            {
                $number++;
                continue;
            }

            $cellIterator = $row->getCellIterator();
            $cellIterator->setIterateOnlyExistingCells(FALSE); // This loops through all cells,

            $i=0;

            $item='';
            foreach ($cellIterator as $cell) {
                $item = $cell->getValue();
                break;
            }

            $model = ORM::factory('airline');
            $model->item =

        */
    }
}